package offer;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder res = new StringBuilder();
        Queue<TreeNode> nodes = new LinkedList<>();
        nodes.add(root);
        while (nodes.size() != 0) {
            TreeNode node = nodes.poll();
            if (node != null) {
                res.append(node.val).append(' ');
                nodes.offer(node.left);
                nodes.offer(node.right);
            } else {
                res.append("n ");
            }
        }
        for (int i = res.length() - 1; i >= 0; i--) {
            if (res.charAt(i) == ' ' || res.charAt(i) == 'n') {
                res.deleteCharAt(i);
            } else {
                break;
            }
        }
        return res.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] s = data.split(" ");
        if (data.length() == 0) {
            return null;
        }
        List<Integer> tree = new ArrayList<>();
        for (String s1 : s) {
            if (s1.charAt(0) == 'n') {
                tree.add(null);
            } else {
                tree.add(Integer.parseInt(s1));
            }
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(new TreeNode(tree.get(0)));
        TreeNode root = queue.peek();
        int i = 1;
        while (i < tree.size()) {
            TreeNode t = queue.poll();
            if (t != null) {
                TreeNode leftChild = (tree.get(i) == null ? null : new TreeNode(tree.get(i)));
                i++;
                t.left = leftChild;
                queue.offer(leftChild);
                if (i < tree.size()) {
                    TreeNode rightChild = (tree.get(i) == null ? null : new TreeNode(tree.get(i)));
                    i++;
                    t.right = rightChild;
                    queue.offer(rightChild);
                }
            }
        }
        return root;
    }
}
